<template>
  <div class="min-h-screen bg-slate-50">
    <TopBar />
    <div class="container mx-auto px-4 py-8">
      <!-- 搜索栏 -->
      <div class="flex flex-col md:flex-row justify-between items-center mb-8">
        <div class="flex items-center mb-4 md:mb-0">
          <div class="text-4xl font-bold text-gray-800 mr-4">Logo</div>
          <div class="text-2xl font-bold text-red-500">购物车</div>
        </div>

        <div class="w-full md:w-2/5">
          <div class="flex h-12 border-2 bg-white border-gray-100 rounded-lg overflow-hidden">
            <input type="search" class="flex-1 px-4 focus:outline-none" placeholder="搜索商品..." v-model="searchName">
            <button class="bg-red-500 text-white px-6 font-bold hover:bg-red-600 transition-colors"
              @click="clickSearch(searchName)">
              全站搜索
            </button>
          </div>
        </div>
      </div>

      <!-- 购物车内容 -->
      <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <!-- 商品列表 -->
        <div class="lg:col-span-3 bg-white rounded-xl shadow-sm overflow-hidden">
          <div class="p-6 border-b border-gray-100">
            <div class="text-xl font-bold text-gray-800">全部商品({{ cartItems.length }})</div>
          </div>

          <div class="p-6">
            <!-- 选择控制 -->
            <div class="flex items-center mb-6">
              <label class="flex items-center cursor-pointer">
                <input type="checkbox" class="w-5 h-5 rounded border-gray-300 text-red-500 focus:ring-red-200"
                  v-model="selectAll">
                <span class="ml-2 text-gray-700">全选</span>
              </label>
              <button
                class="ml-4 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                @click="deleteSelected">
                删除选中
              </button>
            </div>

            <!-- 商品项 -->
            <div v-for="(item, index) in cartItems" :key="item.id || index"
              class="flex flex-col md:flex-row items-start md:items-center p-4 border-b border-gray-100 hover:bg-gray-50 transition-colors">
              <!-- 选择框 -->
              <div class="mb-4 md:mb-0 mr-4">
                <input type="checkbox" class="w-5 h-5 rounded border-gray-300 text-red-500 focus:ring-red-200"
                  v-model="item.selected">
              </div>

              <!-- 商品信息 -->
              <div class="flex-1 flex flex-col md:items-center md:flex-row gap-4">
                <!-- 商品图片 -->
                <div class="w-20 h-20 bg-gray-100 rounded-lg overflow-hidden">
                  <img src="https://picsum.photos/200/200?random=1" alt="商品图片" class="w-full h-full object-cover">
                </div>

                <!-- 商品详情 -->
                <div class="flex-1">
                  <div class="font-medium text-gray-800 mb-1">{{ item.skuName }}</div>
                  <div class="text-sm text-gray-500 flex items-center">
                    <el-icon class="mr-1">
                      <Shop />
                    </el-icon>
                    {{ seller.sellerName || '未知商家' }}
                  </div>
                </div>
                <!-- 规格信息 -->
                <div class="flex-1 text-sm text-gray-600">
                  <div v-for="(spec, idx) in item.skuAttr.split(',')" :key="idx">
                    {{ spec.split(':')[0] }} : {{ spec.split(':')[1] }}
                  </div>
                </div>
                <!-- 价格 -->
                <div class="w-full md:w-auto mt-3 md:mt-0 font-bold text-red-500 md:mr-5">
                  ￥{{ item.skuPrice }}
                </div>

                <!-- 数量 -->
                <div class="w-full md:w-auto mt-3 md:mt-0 flex items-center md:mr-5">
                  <button
                    class="w-8 h-8 flex items-center justify-center border border-gray-300 rounded-l-lg hover:bg-gray-100 transition-colors"
                    @click="item.quantity--">
                    -
                  </button>
                  <div class="w-10 h-8 flex items-center justify-center border-t border-b border-gray-300">
                    {{ item.quantity || 1 }}
                  </div>
                  <button
                    class="w-8 h-8 flex items-center justify-center border border-gray-300 rounded-r-lg hover:bg-gray-100 transition-colors"
                    @click="item.quantity++">
                    +
                  </button>
                </div>

                <!-- 操作 -->
                <div class="w-full md:w-auto mt-3 md:mt-0 ml-auto">
                  <button
                    class="px-4 py-1.5 bg-white border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                    @click="deleteItem(item.cartId)">
                    删除
                  </button>
                </div>
              </div>
            </div>

            <!-- 空购物车提示 -->
            <div v-if="cartItems.length === 0" class="py-12 text-center">
              <el-icon size="60" class="text-gray-300">
                <ShoppingCartFull />
              </el-icon>
              <p class="mt-4 text-gray-500">购物车为空，快去挑选商品吧！</p>
              <button class="mt-4 px-6 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                立即购物
              </button>
            </div>
          </div>
        </div>

        <!-- 结算信息 -->
        <div class="lg:col-span-1">
          <div class="sticky top-24 bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="p-6 border-b border-gray-100">
              <div class="text-xl font-bold text-gray-800">结算明细</div>
            </div>

            <div class="p-6">
              <div class="space-y-4">
                <div class="flex justify-between">
                  <span class="text-gray-600">商品总价</span>
                  <span class="font-medium">￥{{ totalPrice.toFixed(2) }}</span>
                </div>
                <div class="pt-4 border-t border-gray-100 flex justify-between">
                  <span class="font-bold text-lg">实付款</span>
                  <span class="font-bold text-lg text-red-500">￥{{ totalPrice.toFixed(2) }}</span>
                </div>
              </div>

              <button class="w-full mt-6 py-3  text-white font-bold rounded-lg"
                :class="selectedItems.length === 0 ? 'cursor-not-allowed bg-red-300' : 'bg-red-500 hover:bg-red-600'">
                结算 ({{ selectedItems.length }})
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Aside />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import Aside from '@/components/Aside.vue';
import TopBar from '@/components/TopBar.vue';
import { deleteCart, getCart } from '@/apis/cart';
import { useRouter } from 'vue-router';
import { getSellerInfo } from '@/apis/user';
import { ElMessage } from 'element-plus';
const router = useRouter()
// 初始化购物车数据
const cartItems = ref([]);
let searchName = ref('')
const seller = ref()

// selectedItems 逻辑：自动收集所有被选中的商品
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.selected);
});
// 全选/全不选逻辑
const selectAll = computed({
  get() {
    return cartItems.value.length > 0 && cartItems.value.every(item => item.selected);
  },
  set(value) {
    cartItems.value.forEach(item => {
      item.selected = value;
    });
  }
});
const getSeller = async () => {
  let res = await getSellerInfo()
  seller.value = res.data
}
const totalPrice = computed(() => {
  return selectedItems.value.reduce((total, item) => total + item.skuPrice * item.quantity, 0);
})
//获取购物车数据
const getCartData = async () => {
  try {
    const res = await getCart();
    // 初始化每个商品的 selected 属性为 false
    cartItems.value = res.data.map(item => ({ ...item, selected: false }));
  } catch (error) {
    console.error(error);
  }
};
const clickSearch = (name) => {
  router.push(`/items/${name}`)
}
// 删除选中项
const deleteItem = async (id) => {
  try {
    await deleteCart([id])
    getCartData();

    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
};
getCartData();
getSeller()


</script>

<style lang="scss" scoped>
button {
  cursor: pointer;
}

// 自定义复选框样式
input[type="checkbox"] {
  appearance: none;
  -webkit-appearance: none;
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  outline: none;
  cursor: pointer;
  transition: all 0.2s;

  &:checked {
    border-color: #ff4d4f;
    background-color: #ff4d4f;

    &::after {
      content: '';
      display: block;
      width: 6px;
      height: 10px;
      border: solid white;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
      margin: 2px 5px;
    }
  }
}

// 数量调整按钮样式
.quantity-control {
  display: flex;
  align-items: center;

  button {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #e5e7eb;
    background-color: white;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f3f4f6;
    }
  }

  .quantity {
    width: 40px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid #e5e7eb;
    border-bottom: 1px solid #e5e7eb;
  }
}
</style>